package com.ym.medical.service.impl;

import cn.hutool.extra.spring.SpringUtil;
import com.ym.common.constant.Constants;
import com.ym.core.redis.RedisKeyUtil;
import com.ym.core.utils.tkmybatis.BaseSVImpl;
import com.ym.medical.dao.SysConfigDao;
import com.ym.medical.domain.entity.SysConfigEntity;
import com.ym.medical.domain.param.SysConfigQueryParam;
import com.ym.medical.domain.param.SysConfigUpdateParam;
import com.ym.medical.domain.vo.SysConfigListPcVO;
import com.ym.medical.service.ISysConfigSV;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.function.Function;

/**
 * 系统参数配置Service业务层处理
 *
 * @author ym
 * @date 2020-08-18
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class SysConfigSVImpl extends BaseSVImpl<SysConfigEntity, SysConfigDao> implements ISysConfigSV {

	/**
	 * 查询系统参数配置列表
	 *
	 * @param queryParam 系统参数配置 查询参数
	 * @return 系统参数配置
	 */
	@Override
	public List<SysConfigListPcVO> selectListPC(SysConfigQueryParam queryParam) {
		List<SysConfigListPcVO> sysConfigs = mapper.selectListPC(queryParam);
		return sysConfigs;
	}

	/**
	 * 新增系统参数配置
	 *
	 * @param updateParam 系统参数配置 新增参数
	 * @return 结果
	 */
	@Override
	public Long insertPC(SysConfigUpdateParam updateParam) {
		SysConfigEntity entity = updateParam.covert();
		this.insert(entity);
		return entity.getId();
	}

	/**
	 * 修改系统参数配置
	 *
	 * @param updateParam 系统参数配置 修改参数
	 * @return 结果
	 */
	@Override
	public int updateByIdPC(SysConfigUpdateParam updateParam) {
		SysConfigEntity entity = updateParam.covert();
		int result = this.updateById(entity);
		return result;
	}

	@Override
	@Cacheable(value = RedisKeyUtil.KEY_PREFIX + ":" + Constants.System.CACHE_CONFIG, key = "#theKey", unless = "#result == null ")
	public String getValueByKey(String theKey) {
		SysConfigEntity sysConfigs = this.selectOne(
				Select()
						.column("theValue")
						.where()
						.andEqualTo(SysConfigEntity::getTheKey, theKey)
						.end()
		);
		return sysConfigs == null ? null : sysConfigs.getTheValue();
	}

	@Override
	public <R> R getValueByKey(String theKey, Function<String, R> handle) {
		// 这样调用，为了走spring代理缓存
		String valueByKey = SpringUtil.getBean(ISysConfigSV.class).getValueByKey(theKey);
		return handle.apply(valueByKey);
	}
}
